<?php

class UIS_FileReader {
    
    // the readed data from the file
    private $data = array();
    /**
     * array of all the fields in the right order
     * @var type 
     */
    private $names = array();
    
    public function __construct($file, $names = null) {
	
	// read file
	if(($handle = fopen($file, "r")) !== FALSE){
	    
	    // read lines in file
	    while(($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
		$row = array();
		
		// add each element in the data array with the fieldname as key
		for ($c=0; $c < count($data); $c++) {
		    if($names != null && key_exists($c, $names)){
			$row[$names[$c]] = $data[$c];
		    }else{
			$row[$c] = $data[$c];
		    }
		}
		
		$this->data[] = $row;
		
	    }
	    fclose($handle);
	}
	
	return true;
    }
    /**
     * get the total row count
     * @return type 
     */
    public function getTotal(){
	return count($this->data);
    }
    
    /**
     * get all the rows
     * if fields is given, only the given fields will be returned
     * @param type $fields
     * @param array $convert is an array with anonymous functions. keys based on fields
     * @return array of all the rows with convertions if given
     */
    public function getAll($fields = null, $convert = array()){
	if($fields === null){
	    return $this->data;
	}
	
	$output = array();
	
	foreach($this->data as $row){
	    
	    $newRow = array();
	    
	    foreach($fields as $field){
		
		//check if the field is wanted
		if(array_key_exists($field, $row)){
		    
		    // check if there is a convertion function given for this field
		    if(array_key_exists($field, $convert)){
			$newRow[$field] = $convert[$field]($row[$field]);
		    }else{
			$newRow[$field] = $row[$field];
		    }
		}		
	    }
	    
	    $output[] = $newRow;
	}
	
	return $output;
    }
    
}